package com.fdq.dianping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fdq.dianping.entity.Follow;
import com.fdq.dianping.entity.Result;
import com.fdq.dianping.entity.User;
import com.fdq.dianping.entity.dto.UserDto;
import com.fdq.dianping.mapper.FollowMapper;
import com.fdq.dianping.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdq.dianping.service.UserService;
import com.fdq.dianping.util.ThreadLocalUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.fdq.dianping.util.Constants.Follow_Common;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fdq
 * @since 2024-12-29
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //获取登录用户
        //获取当前登录用户信息
        Map<String,Object> userMap = ThreadLocalUtil.get();
        UserDto user = BeanUtil.mapToBean(userMap,UserDto.class,true);

        //判断是关注还是取关
        if(isFollow){
            //关注
            Follow follow = new Follow();
            follow.setUserId(user.getId());
            follow.setFollowUserId(followUserId);
            save(follow);
            //关注信息保存到redis中
            String key = Follow_Common+user.getId();
            stringRedisTemplate.opsForSet().add(key,followUserId.toString());
        }else {
            //取关
            remove(new QueryWrapper<Follow>().eq("user_id", user.getId()).eq("follow_user_id", followUserId));
            //从redis中删除
            String key = Follow_Common+user.getId();
            stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
        }
        return Result.success();
    }

    @Override
    public Result isFollow(Long followUserId) {
        //获取当前登录用户信息
        Map<String,Object> userMap = ThreadLocalUtil.get();
        UserDto user = BeanUtil.mapToBean(userMap,UserDto.class,true);
        Long count = query().eq("user_id", user.getId()).eq("follow_user_id", followUserId).count();

        return Result.success(count > 0);
    }

    /**
     * 使用redis的set数据类型实现求交集
     *
     */
    @Override
    public Result commonFollowers(Long followUserId) {
        //获取当前登录用户信息
        Map<String,Object> userMap = ThreadLocalUtil.get();
        UserDto user = BeanUtil.mapToBean(userMap,UserDto.class,true);

        //求交集
        String userKey = Follow_Common + user.getId();
        String followUserKey = Follow_Common + followUserId;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(userKey, followUserKey);
        stringRedisTemplate.expire(userKey,30, TimeUnit.MINUTES);
        if(intersect == null || intersect.isEmpty()){
            return Result.success();
        }


        //查找共同的用户
        List<Long> ids = intersect.stream().map(Long::valueOf).toList();
        List<UserDto> users = userService.listByIds(ids)
                .stream()
                .map( user1 -> BeanUtil.copyProperties(user1, UserDto.class))
                .toList();

        return Result.success(users);
    }

    @Override
    public Result getFans(Long id) {
        //粉丝关注的信息
        List<Follow> fanRecords = query().eq("follow_user_id", id).list();
        List<UserDto> fans = new ArrayList<>(fanRecords.size());

        for (Follow fanRecord : fanRecords) {
            //获取粉丝id
            Long userId = fanRecord.getUserId();
            //查询用户信息
            User user1 = userService.getById(userId);
            //转dto
            UserDto userDto = BeanUtil.copyProperties(user1, UserDto.class);
            fans.add(userDto);
        }

        return Result.success(fans);
    }

    @Override
    public Result getFollows(Long id) {

        //获取用户关注的人的信息
        List<Follow> followRecords = query().eq("user_id", id).list();
        List<UserDto> follows = new ArrayList<>(followRecords.size());

        for (Follow followRecord : followRecords) {
            //获取关注的用户id
            Long followUserId = followRecord.getFollowUserId();
            //查询用户信息
            User user1 = userService.getById(followUserId);
            //转dto
            UserDto userDto = BeanUtil.copyProperties(user1, UserDto.class);
            follows.add(userDto);
        }
        return Result.success(follows);
    }
}
